package cn.xiaopengstack.infrastructure.persistent.strategy.notify;

import cn.xiaopengstack.domain.trade.adapter.port.ITradePort;
import cn.xiaopengstack.domain.trade.model.entity.NotifyTaskEntity;
import cn.xiaopengstack.domain.trade.model.valobj.NotifyTaskHTTPStatusEnum;
import cn.xiaopengstack.domain.trade.model.valobj.NotifyTypeEnum;
import cn.xiaopengstack.infrastructure.persistent.strategy.model.HttpConfigVO;
import cn.xiaopengstack.types.enums.ResponseCode;
import cn.xiaopengstack.types.exception.AppException;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;

/**
 * @author jiangyangang
 */
@Slf4j
public class HttpNotifyStrategy extends AbstractNotifyStrategy<HttpConfigVO>{

    @Resource
    private ITradePort tradePort;

    public HttpNotifyStrategy(String scene) {
        super(scene);
    }

    @Override
    public void executeNotice(NotifyStrategyFactory.DynamicContext dynamicContext) throws AppException {

        NotifyTaskEntity notifyTaskEntity = dynamicContext.getNotifyTaskEntity();
        String notifyConfig = notifyTaskEntity.getNotifyConfig();
        String notifyPayload = notifyTaskEntity.getNotifyPayload();
        HttpConfigVO httpConfigVO = JSONObject.parseObject(notifyConfig, HttpConfigVO.class);

        String response = tradePort.groupBuyNotify(httpConfigVO.getUrl(), JSONObject.parseObject(notifyPayload));

        if (!NotifyTaskHTTPStatusEnum.SUCCESS.getCode().equals(response)) {
            throw new AppException(ResponseCode.SETTLEMENT_NOTIFY_FAIL);
        }
    }

    @Override
    public NotifyTypeEnum type() {
        return NotifyTypeEnum.HTTP;
    }

    @Override
    public HttpConfigVO getConfig() {
        return null;
    }
}
